<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useAnalysisStore } from '@/stores/analysis'
import { useWorkspaceStore } from '@/stores/workspace'
import FlowManagement from '@/components/FlowManagement.vue'
import { ElMessage } from 'element-plus'
import ComponentsTab from '@/components/ComponentsTab.vue'
import DuplicatesTab from '@/components/DuplicatesTab.vue'
import TimelineTab from '@/components/TimelineTab.vue'
import AIChat from '@/components/AIChat.vue'
import AIConfig from '@/components/AIConfig.vue'
import { useRoute, useRouter } from 'vue-router'
import WorkspaceManager from '@/components/WorkspaceManager.vue'
import LogSearchResultsTab from '@/components/LogSearchResultsTab.vue' // 导入 LogSearchResultsTab 组件
import { 
  DataAnalysis, 
  Upload, 
  UploadFilled, 
  TrendCharts, 
  Grid, 
  Warning, 
  Clock, 
  Setting, 
  ChatDotRound, 
  Download,
  Folder,
  CircleClose,
  Document
} from '@element-plus/icons-vue'

// 状态
const activeMenu = ref('workspace')
const uploadRef = ref()
const route = useRoute()
const router = useRouter()

// 处理来自 ComponentsTab 的查看日志事件
const handleViewLogsFromComponentTab = (payload: { componentName: string, level?: string }) => {
  activeMenu.value = 'log-search-results' // 切换到日志搜索结果页面
  router.push({
    name: 'home',
    query: {
      tab: 'log-search-results',
      component: payload.componentName,
      level: payload.level || undefined // 传递 level，如果没有则为 undefined
    }
  })
}

// Store
const analysisStore = useAnalysisStore()
const workspaceStore = useWorkspaceStore()

// 计算属性
const pageTitle = computed(() => {
  const titles: Record<string, string> = {
    'workspace': '工作区管理',
    'upload': '文件上传',
    'components': '组件分析',
    'duplicates': '重复日志',
    'timeline': '时间分析',
    'ai-chat': 'AI助手',
    'ai-config': 'AI配置',
    'log-search-results': '组件错误日志' // 新增：日志搜索结果页面标题
  }
  return titles[activeMenu.value] || '工作区管理'
})

// 检查是否显示错误类型详情页
const showErrorDetail = computed(() => {
  console.log('showErrorDetail computed, activeMenu:', activeMenu.value, 'route.params.errorType:', route.params.errorType)
  return false // 错误分类功能已移除，始终返回false
})

// 错误类型详情页标题
const errorDetailTitle = computed(() => {
  console.log('errorDetailTitle computed, route.params.errorType:', route.params.errorType)
  return `错误类型详情 - ${route.params.errorType}`
})

// 监听路由参数变化
watch(() => route.params.errorType, (newErrorType) => {
  console.log('route.params.errorType changed:', newErrorType)
  // 错误分类功能已移除，无需处理errorType
  // if (newErrorType) {
  //   activeMenu.value = 'error-detail'
  // }
}, { immediate: true })

// 处理菜单选择
const handleMenuSelect = (index: string) => {
  console.log('handleMenuSelect called with index:', index)
  activeMenu.value = index
  // 如果切换到其他菜单，清除errorType参数
  if (index !== 'error-detail') {
    router.push({ name: 'home' })
  }
  // 如果是Flow管理页面，确保组件已加载
  if (index === 'flows') {
    console.log('Flow管理页面被选中')
  }
}

// 处理文件选择
const handleFileChange = async (file: any) => {
  if (!file.raw.name.endsWith('.tar.gz')) {
    ElMessage.error('请选择 .tar.gz 格式的文件')
    return
  }
  
  const success = await analysisStore.uploadFile(file.raw)
  if (success) {
    // 上传成功后自动切换到组件分析页面
    activeMenu.value = 'components'
  }
}

// 导出数据
const exportData = () => {
  if (!analysisStore.hasData) {
    ElMessage.warning('没有可导出的数据')
    return
  }
  
  const dataStr = JSON.stringify(analysisStore.analysisData, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = `log_analysis_${new Date().toISOString().slice(0, 10)}.json`
  link.click()
  
  URL.revokeObjectURL(url)
  ElMessage.success('数据导出成功')
}

// 初始化
onMounted(async () => {
  // 初始化workspace store
  await workspaceStore.initialize()
  
  // 如果有当前会话且有分析结果，自动加载到analysisStore
  if (workspaceStore.currentSession && workspaceStore.currentSession.analysis_results) {
    analysisStore.setAnalysisFromSession(workspaceStore.currentSession)
  }
})

// 新建或切换工作区时，重置页面状态与分析数据
watch(() => workspaceStore.currentWorkspace?.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    // 回到工作区页面并清理错误详情路由参数
    activeMenu.value = 'workspace'
    if (route.params.errorType) {
      router.push({ name: 'home' })
    }
    // 清理分析数据，禁用依赖数据的菜单
    analysisStore.clearData()
  }
})
</script>

<template>
  <div class="app-container">
    <!-- 左侧导航栏 -->
    <el-aside class="sidebar" width="250px">
      <div class="sidebar-header">
        <div class="logo">
          <el-icon class="logo-icon"><DataAnalysis /></el-icon>
          <span class="logo-text">日志分析系统</span>
        </div>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        class="sidebar-menu"
        @select="handleMenuSelect"
        background-color="#001529"
        text-color="#fff"
        active-text-color="#409eff"
      >
        <el-menu-item index="workspace">
          <el-icon><Folder /></el-icon>
          <span>工作区管理</span>
        </el-menu-item>
        
        <el-menu-item index="upload">
          <el-icon><Upload /></el-icon>
          <span>文件上传</span>
        </el-menu-item>
        
        <el-menu-item index="components" :disabled="!analysisStore.hasData">
          <el-icon><Grid /></el-icon>
          <span>组件分析</span>
        </el-menu-item>
        
        <el-menu-item index="duplicates" :disabled="!analysisStore.hasData">
          <el-icon><Warning /></el-icon>
          <span>重复日志</span>
        </el-menu-item>
        
        <el-menu-item index="timeline" :disabled="!analysisStore.hasData">
          <el-icon><Clock /></el-icon>
          <span>时间分析</span>
        </el-menu-item>
        
        <el-menu-item index="flows">
          <el-icon><Grid /></el-icon>
          <span>Flow管理</span>
        </el-menu-item>
        
        <el-menu-item index="ai-chat">
          <el-icon><ChatDotRound /></el-icon>
          <span>AI助手</span>
        </el-menu-item>
        
        <el-menu-item index="ai-config">
          <el-icon><Setting /></el-icon>
          <span>AI配置</span>
        </el-menu-item>

        <el-menu-item 
          index="log-search-results"
          v-if="activeMenu === 'log-search-results'"
          :disabled="!analysisStore.hasData"
        >
          <el-icon><Document /></el-icon>
          <span>组件错误日志</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区域 -->
    <el-main class="main-content">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <h2 class="page-title">{{ showErrorDetail ? errorDetailTitle : pageTitle }}</h2>
          <!-- 当前会话状态指示器 -->
          <div v-if="workspaceStore.currentWorkspace || workspaceStore.currentSession" class="session-indicator">
            <el-tag v-if="workspaceStore.currentWorkspace" type="info" size="small" class="workspace-tag">
              <el-icon><Folder /></el-icon>
              {{ workspaceStore.currentWorkspace.name }}
            </el-tag>
            <el-tag v-if="workspaceStore.currentSession" type="success" size="small" class="session-tag">
              <el-icon><ChatDotRound /></el-icon>
              {{ workspaceStore.currentSession.name }}
            </el-tag>
          </div>
        </div>
        <div class="toolbar-right">
          <el-button 
            v-if="analysisStore.hasData" 
            @click="exportData"
            type="primary"
            size="small"
          >
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-area">
        <!-- 错误类型详情页面 -->
        <div v-if="false" class="error-detail-page">
          <!-- <ErrorTypeDetail :errorType="String(route.params.errorType)" /> -->
        </div>

        <!-- 其他页面（当不显示错误类型详情时） -->
        <div v-else>
          <!-- 工作区管理页面 -->
          <div v-if="activeMenu === 'workspace'" class="workspace-page">
            <WorkspaceManager />
          </div>

          <!-- 文件上传页面 -->
          <div v-else-if="activeMenu === 'upload'" class="upload-page">
            <el-card class="upload-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <el-icon><Upload /></el-icon>
                  <span>上传日志文件</span>
                </div>
              </template>
              
              <el-upload
                ref="uploadRef"
                class="upload-area"
                drag
                :auto-upload="false"
                :show-file-list="false"
                accept=".tar.gz"
                :on-change="handleFileChange"
                :disabled="analysisStore.loading"
              >
                <el-icon class="upload-icon"><UploadFilled /></el-icon>
                <div class="upload-text">
                  <h3>拖拽文件到此处或点击选择</h3>
                  <p>支持 .tar.gz 格式的压缩包，日志文件位于 LogDump 目录下</p>
                </div>
              </el-upload>

              <!-- 上传进度 -->
              <el-progress 
                v-if="analysisStore.loading" 
                :percentage="analysisStore.uploadProgress" 
                :show-text="false"
                class="upload-progress"
              />
            </el-card>
          </div>

          <!-- 组件分析页面 -->
          <div v-else-if="activeMenu === 'components'" class="components-page">
            <ComponentsTab @view-component-logs="handleViewLogsFromComponentTab" />
          </div>

          <!-- 重复日志页面 -->
          <div v-else-if="activeMenu === 'duplicates'" class="duplicates-page">
            <DuplicatesTab />
          </div>

          <!-- 时间分析页面 -->
          <div v-else-if="activeMenu === 'timeline'" class="timeline-page">
            <TimelineTab />
          </div>

          <!-- AI助手页面 -->
          <div v-else-if="activeMenu === 'ai-chat'" class="ai-chat-page">
            <AIChat />
          </div>

          <!-- AI配置页面 -->
          <div v-else-if="activeMenu === 'ai-config'" class="ai-config-page">
            <AIConfig />
          </div>

          <!-- Flow管理页面 -->
          <div v-else-if="activeMenu === 'flows'" class="flows-page">
            <FlowManagement />
          </div>

          <!-- 日志搜索结果页面 -->
          <div v-else-if="activeMenu === 'log-search-results'" class="log-search-results-page">
            <LogSearchResultsTab 
              :component-name="route.query.component as string" 
              :log-level="route.query.level as string"
            />
          </div>
        </div>
      </div>
    </el-main>
  </div>
</template>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  background: #f0f2f5;
  overflow: auto;
}

.sidebar {
  background: #001529;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  flex-shrink: 0;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #1f2937;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-icon {
  font-size: 20px;
  color: #409eff;
}

.logo-text {
  color: #fff;
  font-size: 16px;
  font-weight: 600;
}

.sidebar-menu {
  border: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.sidebar-menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  margin: 4px 12px;
  border-radius: 6px;
  color: #ffffff !important;
}

.sidebar-menu :deep(.el-menu-item:hover) {
  background-color: #1f2937 !important;
  color: #ffffff !important;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background-color: #409eff !important;
  color: #ffffff !important;
}

.sidebar-menu :deep(.el-menu-item.is-disabled) {
  color: #9ca3af !important;
  background-color: transparent !important;
}

.main-content {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow: auto;
  min-width: 0;
}

.toolbar {
  height: 60px;
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--color-heading);
}

.session-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.workspace-tag,
.session-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.workspace-tag .el-icon,
.session-tag .el-icon {
  font-size: 12px;
}

.content-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 0;
  background: transparent;
}

.upload-page {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 24px;
}

.upload-card {
  width: 100%;
  max-width: 100%;
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.upload-area {
  width: 100%;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  height: 300px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  background: #f9fafb;
  transition: all 0.3s;
}

.upload-area :deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-icon {
  font-size: 64px;
  color: #9ca3af;
  margin-bottom: 24px;
}

.upload-text h3 {
  margin: 0 0 16px 0;
  color: var(--color-text);
  font-size: 20px;
}

.upload-text p {
  margin: 0;
  color: var(--color-text);
  font-size: 14px;
}

.upload-progress {
  margin-top: 16px;
}

.components-page,
.duplicates-page,
.timeline-page,
.ai-config-page,
.flows-page,
.log-search-results-page {
  height: 100%;
  width: 100%;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.ai-chat-page {
  height: 100%;
  width: 100%;
  background: transparent;
  border-radius: 12px;
  overflow: hidden;
}

.error-detail-page {
  height: 100%;
  width: 100%;
  position: relative;
  overflow: hidden;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding-bottom: 60px; /* 减少底部空白 */
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-area {
    padding: 20px;
  }
  
  .upload-card {
    max-width: 90%;
  }
}

@media (max-width: 768px) {
  .app-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100% !important;
    height: auto;
    flex-shrink: 0;
  }
  
  .sidebar-header {
    height: 50px;
  }
  
  .sidebar-menu {
    height: auto;
    display: flex;
    overflow-x: auto;
    overflow-y: hidden;
  }
  
  .sidebar-menu :deep(.el-menu-item) {
    margin: 4px 8px;
    min-width: 120px;
    flex-shrink: 0;
  }
  
  .toolbar {
    padding: 0 16px;
  }
  
  .content-area {
    padding: 16px;
    flex: 1;
  }
  
  .upload-area :deep(.el-upload-dragger) {
    height: 200px;
  }
  
  .upload-icon {
    font-size: 48px;
  }
  
  .upload-text h3 {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .logo-text {
    font-size: 14px;
  }
  
  .page-title {
    font-size: 16px;
  }
  
  .content-area {
    padding: 12px;
  }
  
  .upload-area :deep(.el-upload-dragger) {
    height: 150px;
  }
  
  .upload-icon {
    font-size: 36px;
  }
  
  .upload-text h3 {
    font-size: 16px;
  }
  
  .upload-text p {
    font-size: 12px;
  }
}

/* 确保内容区域铺满 */
.content-area > div {
  height: 100%;
  width: 100%;
}
</style>
